package remote_work.core.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ibm.icu.text.SimpleDateFormat;

import remote_work.dto.InputObject;
import remote_work.dto.OutputObject;
import remote_work.util.DBHelper;
import remote_work.util.MyService;
import remote_work.util.SystemConstants;

/**
 * @author LiuPing
 *
 * 2018年3月23日
 */
@MyService
public class FileService {
	
//	private String isUsing = "使用中";
//	private String deleted = "已删除";
	
	/**
	 * 获取文件：教师获取自己添加的作业 ，学生根据班级和课程获取可用作业 
	 * 
	 * @param inputObject
	 * @return
	 * @throws Exception
	 */
	public OutputObject getFiles(InputObject inputObject) throws Exception {
		System.out.println("获取文件列表");
		OutputObject outputObject = new OutputObject();
		DBHelper dao = new DBHelper();
		List<Object> params = new ArrayList<>();
		String state=(String) inputObject.getValue("state");
		if(state.indexOf(",")>=0){
			
			String[] states = state.split(",");
			state="";
			for(String sta:states){
				state+="'"+sta+"'"+",";
			}
			state=state.substring(0, state.lastIndexOf(","));
		}else{
			state="'"+state+"'";
		}
		System.out.println(state);
		String sql = "select * from fileinfo a,userinfo b where a.uploadperson=b.username and a.state in ("+state+")";
		//params.add(inputObject.getValue("state"));
		if (inputObject.getValue("uploadPerson") != null && !"".equals(inputObject.getValue("uploadPerson"))) {
			sql += " and a.uploadperson = ?"; // 查询自己上传的文件
			params.add(inputObject.getValue("uploadPerson"));
		}
		if (inputObject.getValue("clazz") != null && !"".equals(inputObject.getValue("clazz"))) {
			sql += " and a.clazz = ?"; // 查询自己上传的文件
			params.add(inputObject.getValue("clazz"));
		}
		System.out.println("作业"+sql);
		outputObject.setBeans(dao.find(sql, params));
		
		return outputObject;
	}
	
	/**
	 * 删除文件：删除磁盘上的文件，但是不删除数据库中的记录，只改变一下状态
	 * 
	 * @param inputObject
	 * @return
	 */
	public OutputObject deleteFile(InputObject inputObject) throws Exception {
		System.out.println("删除文件");
		OutputObject outputObject = new OutputObject();
		DBHelper dao = new DBHelper();
		List<Object> params = new ArrayList<>();
		String sql = "update fileinfo set state = '已删除' where fileid = ?";
		params.add(inputObject.getValue("fileId"));
		int doUpdate = dao.doUpdate(sql, params);
		if (doUpdate <= 0) {
			outputObject.setReturnMessage("");
		}
		return outputObject;
	}

	/**
	 * 上传文件
	 * 
	 * @param inputObject
	 * @return
	 */
	public OutputObject uploadFile(InputObject inputObject) throws Exception {
		System.out.println("上传文件");
		OutputObject outputObject = new OutputObject();
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
			File file = (File) inputObject.getValue("file");
			if (file == null) {
				outputObject.setReturnCode("-1");
				outputObject.setReturnMessage("文件未找到");
				return outputObject;
			}
			// 数据库操作
			DBHelper dao = new DBHelper();
			Date date = new Date();
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
			
			String fileId = "FILE"+String.valueOf(date.getTime());
			String fileName = file.getName();
			String fileAbsolutelyPath = SystemConstants.UPLOADPATH+fileName;
			String uploadDate = simpleDateFormat.format(date);
			String validDate = (String)inputObject.getValue("validDate");
			String sql = "insert into fileinfo(fileid,filename,course,clazz,filepath,filetype,validdate,uploaddate,uploadperson,state) "
					+ "values(?,?,?,?,?,?,?,?,?,?)";
			List<Object> params = new ArrayList<>();
			params.add(fileId);
			params.add(fileName);
			params.add((String)inputObject.getValue("course"));
			params.add((String)inputObject.getValue("clazz"));
			params.add(fileAbsolutelyPath);
			params.add(fileName);
			params.add(validDate);
			params.add(uploadDate);
			params.add(inputObject.getValue("uploadPerson"));
			params.add(inputObject.getValue("state"));
			dao.doUpdate(sql, params);
			Map<String, Object> bean = new HashMap<>();
			bean.put("fileId", fileId);
			bean.put("fileName", fileName);
			bean.put("uploadDate", uploadDate);
			bean.put("validDate", validDate);
			outputObject.setBean(bean);
			// 入库之后开始把文件写到服务器
			fis = new FileInputStream(file);
			File newFile = new File(fileAbsolutelyPath);
			if (!newFile.exists()) {
				File dir = new File(SystemConstants.UPLOADPATH);
				if (!dir.exists()) {
					dir.mkdirs();
				}
				newFile.createNewFile();
			}
			fos = new FileOutputStream(newFile);
			byte[] b = new byte[1024];
			while (fis.read(b) != -1) {
				fos.write(b);
				fos.flush();
			}
		} catch (FileNotFoundException e) {
			outputObject.setReturnCode("-1");
			outputObject.setReturnMessage("文件没找到");
		} catch (IOException e) {
			outputObject.setReturnCode("-1");
			outputObject.setReturnMessage("文件存储失败");
		} finally {
			try {
				if (fos != null) {
					fos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return outputObject;
	}
	
	public OutputObject uploadFile1(InputObject inputObject) throws Exception {
		System.out.println("上传文件uploadFile1");
		OutputObject outputObject = new OutputObject();
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
			File file = (File) inputObject.getValue("file");
			if (file == null) {
				outputObject.setReturnCode("-1");
				outputObject.setReturnMessage("文件未找到");
				return outputObject;
			}
			// 数据库操作
			DBHelper dao = new DBHelper();
			Date date = new Date();
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			
			String fileId = "FILE"+String.valueOf(date.getTime());
			String fileName = (String) inputObject.getValue("newFileName");
			String sqlNum="select * from fileinfo where filename like '%"+fileName+"%'";
			
			List<Map<String, Object>> fileNameNum = dao.find(sqlNum, null);
			
			fileName=fileName+"_"+"第"+(fileNameNum.size()+1)+"次作业";
			String fileAbsolutelyPath = SystemConstants.UPLOADPATH+fileName;
			String uploadDate = simpleDateFormat.format(date);
			String validDate = (String)inputObject.getValue("validDate");
			String sql = "insert into fileinfo(fileid,filename,course,clazz,filepath,filetype,validdate,uploaddate,uploadperson,state) "
					+ "values(?,?,?,?,?,?,?,?,?,?)";
			String querySql = "select * from fileinfo where filename='" + file.getName() +"'";
			List<Map<String, Object>> find = dao.find(querySql, null);
			if(find.size()<1){
				outputObject.setReturnCode("-1");
				outputObject.setReturnMessage("该文件不是老师要求的作业文件不能上传!");
				return outputObject;
			}
			System.out.println(find.toString());
			Date date1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse((String)find.get(0).get("validdate"));
			if(date.getTime()>date1.getTime()){
				outputObject.setReturnCode("-1");
				outputObject.setReturnMessage("作业提交时间已超过，不能再提交该作业了!");
				return outputObject;
			}
			List<Object> params = new ArrayList<>();
			params.add(fileId);
			params.add(fileName);
			params.add((String)find.get(0).get("course"));
			params.add((String)inputObject.getValue("clazz"));
			params.add(fileAbsolutelyPath);
			params.add(fileName);
			params.add(validDate);
			params.add(uploadDate);
			params.add(inputObject.getValue("uploadPerson"));
			params.add(inputObject.getValue("state"));
			dao.doUpdate(sql, params);
			Map<String, Object> bean = new HashMap<>();
			bean.put("fileId", fileId);
			bean.put("fileName", fileName);
			bean.put("uploadDate", uploadDate);
			bean.put("validDate", validDate);
			outputObject.setBean(bean);
			// 入库之后开始把文件写到服务器
			fis = new FileInputStream(file);
			File newFile = new File(fileAbsolutelyPath);
			if (!newFile.exists()) {
				File dir = new File(SystemConstants.UPLOADPATH);
				if (!dir.exists()) {
					dir.mkdirs();
				}
				newFile.createNewFile();
			}
			fos = new FileOutputStream(newFile);
			byte[] b = new byte[1024];
			while (fis.read(b) != -1) {
				fos.write(b);
				fos.flush();
			}
		} catch (FileNotFoundException e) {
			outputObject.setReturnCode("-1");
			outputObject.setReturnMessage("文件没找到");
		} catch (IOException e) {
			outputObject.setReturnCode("-1");
			outputObject.setReturnMessage("文件存储失败");
		} finally {
			try {
				if (fos != null) {
					fos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return outputObject;
	}
	
	public OutputObject downloadFile(InputObject inputObject) throws Exception {
		System.out.println("下载文件downloadFile");
		OutputObject outputObject = new OutputObject();
		String fileName = (String) inputObject.getValue("fileName");
		DBHelper db = new DBHelper();
		List<Object> params = new ArrayList<>();
		String sql = "select filepath from fileinfo where filename = ?";
		params.add(fileName);
		List<Map<String, Object>> find = db.find(sql, params);
		if (find.size() > 0) {
			String filePath = (String) find.get(0).get("filepath");
			File file = new File(filePath);
			outputObject.addObject("filePath", filePath);
			outputObject.addObject("file", file);
			outputObject.addObject("fileName", fileName);
		} else {
			outputObject.setReturnCode("-1");
		}
		return outputObject;
	}
	//打分
	public OutputObject updateScore(InputObject inputObject) throws Exception{
		System.out.println("更新分数updateScore");
		String sql = "update fileinfo set state='已批改', score=? where fileid=?";
		DBHelper db = new DBHelper();
		List<Object> params = new ArrayList<>();
		params.add(inputObject.getValue("score"));
		params.add(inputObject.getValue("fileId"));
		//System.out.println("更新分数updateScore"+sql+inputObject.getParams().get("score")+inputObject.getParams().get("fileId"));
		int find = db.doUpdate(sql, params);
		
		OutputObject outputObject = new OutputObject();
		
		if(find > 0){
			outputObject.setReturnCode("0");
			outputObject.setReturnMessage("打分成功！");
		}else{
			outputObject.setReturnCode("-1");
			outputObject.setReturnMessage("打分失败！");
		}
		return outputObject;
	}
}
